package top.szhome.framework.starter.db.meta;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import top.szhome.framework.starter.auth.AuthContext;
import top.szhome.framework.starter.auth.util.AuthUtil;

import java.util.Date;

/**
 * 字段自动填充
 *
 * @author 唐加利
 * @date 2023/7/27
 **/
@ConditionalOnClass(AuthUtil.class)
@Component
@Slf4j
public class AutoFillHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("插入时自动填充字段, names={}", metaObject.getGetterNames());

        AuthContext context = AuthUtil.getContext();
        this.strictInsertFill(metaObject, "createUser", String.class, String.valueOf(context.getUserId()));
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateUser", String.class, String.valueOf(context.getUserId()));
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("更新时自动填充字段, names={}", metaObject.getGetterNames());

        AuthContext context = AuthUtil.getContext();
        this.strictUpdateFill(metaObject, "updateUser", String.class, String.valueOf(context.getUserId()));
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
    }
}
